package com.koi.limit.aspect;

import com.koi.common.anno.KoiLimit;
import com.koi.common.enums.limit.LimitType;
import com.koi.common.ex.koi.ParamsException;
import com.koi.common.utils.ip.IpUtil;
import com.koi.limit.config.KoiRedisLimitUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

/**
 * @author ･ᴗ･
 * @description [KoiLimitAspect限流处理]
 */
@Slf4j
@Aspect
@Order(2)
@Component
public class KoiLimitAspect {

    @Autowired
    private KoiRedisLimitUtil koiRedisLimitUtil;

    /**
     * @description [前置通知，判断是否超出限流次数】
     */
    @Before("@annotation(limit)")
    public void doBefore(JoinPoint point, KoiLimit limit) {
        try {
            log.info("限流开始进入------------->");
            // 拼接key
            String key = getCombineKey(limit, point);
            // 判断是否超出限流次数
            if (!koiRedisLimitUtil.limit(key, limit.count(), limit.time())) {
                throw new ParamsException("访问过于频繁，请稍候再试");
            }
        } catch (ParamsException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("接口限流异常，请稍候再试");
        }
    }

    /**
     * @description [根据限流类型拼接key】
     */
    public String getCombineKey(KoiLimit limit, JoinPoint point) {
        // 获取服务请求的对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuilder sb = new StringBuilder(limit.prefix());
        // 按照IP限流
        if (limit.type() == LimitType.IP) {
            String ipAddr = IpUtil.getIpAddr(request);
            sb.append(ipAddr).append(":");
            log.info("限流IP：{}", ipAddr);
        }
        // 拼接类名和方法名
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        sb.append(targetClass.getName()).append("-").append(method.getName());
        return sb.toString();
    }

}
